﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SA2012TBRace
{
	public static class Helper
	{
		static double _EarthRadius = 6366;
		static double _d2r = (Math.PI / 180D);

		private static double GetEarthRadiusAtLatitude(double latitude)
		{
			return 3963 - (13 * Math.Sin(Degree2Radius(latitude)));
		}

		public static double CalculateDistance(double lat1, double lon1, double lat2, double lon2)
		{
			double t = lon1 - lon2;
			
			double distance = Math.Sin(Degree2Radius(lat1)) * Math.Sin(Degree2Radius(lat2)) 
				+  Math.Cos(Degree2Radius(lat1)) * Math.Cos(Degree2Radius(lat2)) * Math.Cos(Degree2Radius(t));
			
			distance = Math.Acos(distance);
			distance = Radius2Degree(distance);
			distance = distance * 60 * 1.1515 * 1.6;

			return distance;
		}

		private static double Degree2Radius(double deg)
		{
			return (deg * Math.PI / 180.0);
		}

		private static double Radius2Degree(double rad)
		{
			return rad / Math.PI * 180.0;
		}

		public static double CalculateGreatCircleDistance(double lat1, double long1, double lat2, double long2, double radius)
		{
			return radius * Math.Acos(
				Math.Sin(lat1) * Math.Sin(lat2)
				+
				Math.Cos(lat1) * Math.Cos(lat2) * Math.Cos(long2 - long1));
		}

		public static double CalculateGreatCircleDistanceOther(double lat1, double lon1, double lat2, double lon2, double radius)
		{
			return Math.Acos(
				Math.Cos(lat1) * Math.Cos(lon1) * Math.Cos(lat2) * Math.Cos(lon2)
				+
				Math.Cos(lat1) * Math.Sin(lon1) * Math.Cos(lat2) * Math.Sin(lon2)
				+ Math.Sin(lat1) * Math.Sin(lat2)
				) * radius;
		}
		
		public static double HaversineInKM(double lat1, double long1, double lat2, double long2)
		{
			double dlong = (long2 - long1) * _d2r;
			double dlat = (lat2 - lat1) * _d2r;
			double a = Math.Pow(Math.Sin(dlat / 2D), 2D) + Math.Cos(lat1 * _d2r) * Math.Cos(lat2 * _d2r) * Math.Pow(Math.Sin(dlong / 2D), 2D);
			double c = 2D * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1D - a));
			double d = _EarthRadius * c;

			return d;
		}
	}
}